import com.mongodb.*;
import com.mongodb.MongoClient;
import com.mongodb.client.*;
import com.mongodb.client.model.Filters;
import org.bson.Document;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Test2 {
    public static void main(String[] args){
        try {
            // 连接池
            MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
            builder.connectTimeout(5000); // 连接超时
            builder.socketTimeout(5000); // 读写超时
            builder.connectionsPerHost(30); // 每个地址的最大连接数

            // 提供用户名和密码
            // MongoCredential credential = MongoCredential.createScramSha1Credential("username", "databaseName", "password".toCharArray());

            // 集群访问， 请求地址传入多个
            MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress("192.168.0.103", 27017)), builder.build());
            // 连接时校验用户
            // MongoClient mongoClient = new MongoClient(Arrays.asList(new ServerAddress("192.168.0.103", 27017)), credential, builder.build());

            MongoDatabase mongoDatabase = mongoClient.getDatabase("test");

            MongoCollection<Document> collection = mongoDatabase.getCollection("test");

            FindIterable<Document> result = collection.find().limit(2).skip(2).sort(new Document("age", 1));
            MongoCursor<Document> cursor = result.iterator();
            while(cursor.hasNext()){
                Document doc = cursor.next();
                System.out.print("find all : [ { doc : " + doc + " }, ");
                System.out.print("{ name : " + doc.getString("name") + " }, ");
                System.out.println("{ age : " + doc.get("age") + " } ]");
            }

            /*Document param = new Document();
            param.append("_id", null);
            param.append("count", new Document("$sum", 1));

            Document options = new Document();
            options.append("$project", new Document("count", 1).append("_id", 0));
            AggregateIterable<Document> result = collection.aggregate(Arrays.asList(new Document("$group", param), options));
            MongoCursor<Document> cursor = result.iterator();
            while(cursor.hasNext()){
                System.out.println(cursor.next());
            }*/

        } catch (Exception e) {
            System.err.println( e.getClass().getName() + ": " + e.getMessage() );
        }
    }
}
